from typing import Any, Dict

import httpx


def search_impl(query: str) -> Dict[str, Any]:
    """
    调用每日一言接口
    """
    r = httpx.get("https://v1.hitokoto.cn", params={"c": query})
    return r.json()


def search(arguments: Dict[str, Any]) -> Any:
    query = arguments["query"]
    result = search_impl(query)
    return {"result": result}


def write_code_impl(code: str):
    """
    将代码写入页面
    """
    try:
        # 打开文件 'new.html'，以写入模式 ('w')
        with open('new.html', 'w', encoding='utf-8') as file:
            file.write(code)
        return "文件写入成功！"
    except Exception as e:
        return f"文件写入失败: {str(e)}"


def write_code(arguments: Dict[str, Any]) -> Any:
    code = arguments["code"]
    result = write_code_impl(code)
    return {"result": result}


# 通过 tool_map 将每个工具名称及其对应的函数进行映射，以便在 Kimi 大模型返回 tool_calls 时能快速找到应该执行的函数
tool_map = {
    "WriteCode": write_code,
    "search": search
}
